import {AsyncStorage, DeviceEventEmitter, PermissionsAndroid, Platform, CameraRoll, Alert} from 'react-native'
import IparNetwork, {SERVER_TYPE} from "../httpUtils/IparNetwork";
import I18n from '../res/language/i18n'
import moment from 'moment';
import ArticleDetail from "../pages/article/ArticleDetail";
import GoodsPage from "../pages/common/GoodsPage";
import CategoryMinPage from "../pages/category/CategoryMinPage";
import MyCommonJavaJs from "./MyCommonJavaJs";

export default class CommonUtils {

    /**
     * 图片下载到本地
     */
    static downloadImage(url) {
        CommonUtils.showLoading();
        if (Platform.OS === 'ios') {
            let promise = CameraRoll.saveToCameraRoll(url);
            promise.then((data) => {
                    CommonUtils.dismissLoading();
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                }, () => {
                    CommonUtils.dismissLoading();
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            )
        } else {
            new MyCommonJavaJs().downloadImage(url, () => {
                DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                CommonUtils.dismissLoading();
            }, () => {
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                CommonUtils.dismissLoading();
            });
        }
    }

    /**
     * 各位国家的信息（swap_amount....）
     * @param region_id
     * @returns {null}
     */
    savePvAmount(region_id) {
        if (!region_id) return null;
        let iparNetwork = new IparNetwork();
        iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getPv?', 'region_id=' + region_id)
            .then((result) => {
                if (result.code === 200) {
                    let data = result.data;
                    /**
                     pv_id: 1,
                     region_id: "CN",
                     region_name: "China",
                     pv_amount: 1,
                     swap_amount: 6.4,
                     currency_code: "￥",
                     currency_name: "RMB",
                     add_time: "2018-07-11 11:46:17",
                     last_time: "2018-07-11 11:46:17",
                     user_id: 10,
                     reward_plan: "1,2,3",
                     sort: null
                     */
                    AsyncStorage.setItem('getPv', data ? JSON.stringify(data) + '' : 'null', (error, result) => {
                        DeviceEventEmitter.emit('upLoadData')
                    });


                } else {//如果code等于500的话重新请求美国的
                    this.savePvAmount('US');
                }
            })
            .catch((error) => {
                console.log(error);
            });
    }


    /**
     * 国家到信息保存到本地
     * @param data
     */
    saveCountryData(data) {
        if (!data) return;
        /**{
            id: 96495,
            iso: "KZ",
            country: "Kazakhstan",
            language: "EN",
            level: 0,
            type: "Country",
            name: "Kazakhstan",
            area_code: "+7",
            currency: "KZT",
            address: "Kazakhstan",
        } */


        /**
         * 判断各位国家的默认语言
         * @type {string}
         * @private
         */
        // let _lang = 'en';
        // switch (data.iso) {
        //     case 'CN':
        //         _lang = 'zh';
        //         break;
        //     case 'KZ':
        //     case 'KG':
        //     case 'RU':
        //     case 'AZ':
        //         _lang = 'ru';
        //         break;
        // }
        // I18n.locale = _lang;
        // AsyncStorage.setItem('lang', _lang);


        AsyncStorage.setItem('country_id', data.id ? data.id + '' : 'null');
        AsyncStorage.setItem('country_iso', data.iso ? data.iso + '' : 'null');
        AsyncStorage.setItem('country', data.country ? data.country + '' : 'null');
        AsyncStorage.setItem('country_language', data.language ? data.language + '' : 'null');
        AsyncStorage.setItem('country_level', data.level ? data.level + '' : 'null');
        AsyncStorage.setItem('country_type', data.type ? data.type + '' : 'null');
        AsyncStorage.setItem('country_name', data.name ? data.name + '' : 'null');
        AsyncStorage.setItem('country_area_code', data.area_code ? data.area_code + '' : 'null');
        AsyncStorage.setItem('country_currency', data.currency ? data.currency + '' : 'null');
        AsyncStorage.setItem('country_address', data.address ? data.address + '' : 'null');

        /**
         * 国家改的时候一定要更新本地的各位国家的信息（swap_amount。。。）
         */
        // new CommonUtils().savePvAmount(data.iso);
    }


    static saveUserInfo(userData, callback) {
        if (!userData) return;
        /**
         user_id: "b1472464-6b46-cfe7-bee9-f5acb58c3bd0",
         mobile: "1389999999",
         user_name: "vitamin",
         nick_name: "bazar",
         head_img: "/upload/image/20180614/1528942883306714.png",
         lang:ug"country: "KZ",
         */
        AsyncStorage.setItem('userInfo', userData ? JSON.stringify(userData) + '' : 'null', callback);


        // /**
        //  * 国家改的时候一定要更新本地的各位国家的信息（swap_amount。。。）
        //  */
        // if (isUpdateCountryInfo) {
        //     new CommonUtils().savePvAmount(userData.country);
        // }

    }

    /**
     * 获取本地的数据
     * @param key
     */
    static getAcyncInfo(key) {
        return new Promise((resolve, reject) => {
            AsyncStorage.getItem(key, (error, result) => {
                if (result) {
                    resolve(result)
                } else {
                    reject(error)
                }
            });
        })
    }


    /**
     * A => B => C => D 从D页面跳B （删除C页面）
     * @param _this
     * @param name
     */
    popToRoute(_this, name) {
        let routes = _this.props.navigator.state.routeStack;
        let destinationRoute = '';
        for (let i = routes.length - 1; i >= 0; i--) {
            if (routes[i].name === name) {
                destinationRoute = _this.props.navigator.getCurrentRoutes()[i];
                _this.props.navigator.popToRoute(destinationRoute);
                return;
            }
        }
    }


    /**
     * clone data
     */
    static cloneArray(ayyar) {
        if (!ayyar) return;
        let resultData = [];
        for (let i = 0, len = ayyar.length; i < len; i++) {
            resultData.push(ayyar[i])
        }
        return resultData;
    }

    /**
     * 是否密码
     * @param password
     * @returns {boolean}
     */
    static isPassword(password) {
        if (!password) return false;
        if (password.length <= 7) return false;
        const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/;
        return reg.test(password);
    }


    /**
     *
     * @param year
     * @returns {boolean}
     */
    ageOf18(year) {
        if (!year) return false;
        let _moment = moment(new Date());
        let format = _moment.format("YYYY");
        let element = year.split('/')[0];
        if (format - element > 18) {
            return true;
        } else if (format - element === 18) {
            return _moment.format("MM") - year.split('/')[1] >= 0;
        }
        return false;
    }


    phoneEncryption(phone) {

        let length = phone.length;
        if (length <= 4) return phone;

        let leftStr = phone.substring(0, 2);
        let rightStr = phone.substring(length, length - 1);
        let centerStr = '******';
        if (length > 5) {
            leftStr = phone.substring(0, 3);
            rightStr = phone.substring(length, length - 2);
            centerStr = '';
            for (let i = 5; i < length; i++) {
                centerStr = centerStr + '*'
            }
        }
        return leftStr + centerStr + rightStr;
    }


    /**
     * 订单状态
     * @param orderStatus
     * @param returnType
     * @return {*}
     */
    orderStatus(orderStatus, returnType) {

        let status;
        switch (orderStatus) {
            case (0)://待审核订单
                status = I18n.t('default.notConfirmed');
                break;
            case (1)://待支付订单
                status = I18n.t('default.unpaid');
                break;
            case (2):
            case (3)://已支付
                status = I18n.t('default.paid');
                break;
            case (4):
            case (5):
            case (6):
            case (7):
            case (8):
            case (9):
            case (10)://在处理
                status = I18n.t('default.processing');
                break;
            case (11)://准备发货
                status = I18n.t('default.readyToShip');
                break;
            case (12)://配货中
                status = I18n.t('o.returning');
                break;
            case (13)://已发货
                status = I18n.t('default.shipped');
                break;
            case (88)://已完成
                status = I18n.t('default.completed');
                break;
            case (21)://未发货申请退款
                status = I18n.t('default.appliedRefund');
                break;
            case (22)://已收货申请退货
                status = I18n.t('default.appliedForRefund');
                break;
            case (23)://已同意退货
                status = I18n.t('default.appliedToReturn');
                break;
            case (24)://已同意，待客户退货
                status = I18n.t('default.returning');
                break;
            case (25)://已收退货，待验收
                status = I18n.t('default.returningOne');
                break;
            case (26)://已验收，待退款
                status = I18n.t('default.reviewingReturn');
                break;
            case (27)://同意退款，退款
                status = I18n.t('default.refundApproved');
                break;
            case (28)://已退款
                status = I18n.t('default.refunded');
                break;
            case (29)://收款确认
                status = I18n.t('default.received');
                break;
            case (30)://已完成
                status = I18n.t('default.completed');
                break;
            case (44)://取消
                status = I18n.t('default.cancel');
                break;
        }
        return status;
    }


    /**
     * 获取优化权限（相机）
     */
    requestCameraPermission() {
        if (Platform.OS === 'ios') return;
        try {
            PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA);
        } catch (err) {
            console.warn(err)
        }
    }


    addDate(_date, days) {
        if (!days) {
            return _date;
        }
        let date = new Date(_date);
        date.setDate(date.getDate() + days);
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hours = date.getHours();
        let minutes = date.getMinutes();
        let seconds = date.getSeconds();
        return date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day) + ' ' + getFormatDate(hours) + ':' + getFormatDate(minutes) + ':' + getFormatDate(seconds);
    }


    getMonthsData(month) {
        let newVar = [{
            name: I18n.t('monthsJson.whole'),
            code: '01',
        }, {
            name: I18n.t('monthsJson.january'),
            code: '01',
        }, {
            name: I18n.t('monthsJson.february'),
            code: '02',
        }, {
            name: I18n.t('monthsJson.march'),
            code: '03',
        }, {
            name: I18n.t('monthsJson.april'),
            code: '04',
        }, {
            name: I18n.t('monthsJson.may'),
            code: '05',
        }, {
            name: I18n.t('monthsJson.june'),
            code: '06',
        }, {
            name: I18n.t('monthsJson.july'),
            code: '07',
        }, {
            name: I18n.t('monthsJson.august'),
            code: '08',
        }, {
            name: I18n.t('monthsJson.september'),
            code: '09',
        }, {
            name: I18n.t('monthsJson.october'),
            code: '10',
        }, {
            name: I18n.t('monthsJson.november'),
            code: '11',
        }, {
            name: I18n.t('monthsJson.december'),
            code: '12',
        },];

        if (month) {
            newVar.splice(0, 1);
        }

        return newVar
    }

    /*


   level==0 => goods_pv *swap_amount

   if (is_discont==1){
       level==0 => goods_pv  * ((100-percent_own)/100)*swap_amount
   }else{
       level==0 => goods_pv *swap_amount
   }

    if (is_discont==1){
   level >0 => shop_pv * ((100-percent_own)/100)*swap_amount
   }

    */

    getNewVipPrice(userData, goodsInfo, swap_amount) {
        if (!userData) return 0;
        if (!userData.user_level) return 0;

        if (!goodsInfo) return 0;
        let userLevel = userData.user_level;

        console.log(userLevel);
        let price = 0;
        if (userLevel.level > 0) {
            if (userLevel.is_discount === 1) {
                price = goodsInfo.shop_pv * ((100 - userLevel.percent_own) / 100) * swap_amount
            } else {
                price = goodsInfo.shop_pv * swap_amount
            }
        } else {
            if (userLevel.is_discount === 1) {
                price = goodsInfo.shop_pv * ((100 - userLevel.percent_own) / 100) * swap_amount
            }
        }
        return price;
    }

    /**
     * IBM 用户的价格
     */
    getPercentOwnAmount(goodsInfo, swapAmount, userData) {
        if (!userData) return 0;
        let userLevel = userData.user_level;
        if (!userLevel) return 0;
        if (!goodsInfo) return 0;
        if (userLevel.is_discount === 0) return 0;
        if (userLevel.percent_own <= 0) return 0;


        if (userData.is_real_shop === 1 && userLevel.level > 11) {
            // return (goodsInfo.shop_pv * swapAmount) * (userData.shop_percent / 100);
            return (goodsInfo[this._getShopPv(userLevel.level)] * swapAmount);
        } else {
            return (goodsInfo.goods_pv * swapAmount) - ((goodsInfo.goods_bv * swapAmount) * (userLevel.percent_own / 100));
        }
    }

    _getShopPv(_level) {
        let level = _level - 12;
        if (level == 0) {
            return 'shop_pv'
        } else {
            return 'shop' + level + '_pv'
        }
    }


    static checkEmail(email) {
        if (!email) return false;
        let reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
        return reg.test(email.trim())
    }


    static showLoading() {
        DeviceEventEmitter.emit('loading', true)
    }


    static dismissLoading() {
        DeviceEventEmitter.emit('loading', false)
    }


    /**
     * 点击广告
     */
    onClickAdvers(rowData, _this, countryIso) {

        let _component = null;
        let _params = null;
        switch (rowData.rel_type) {
            case 1://产品
                _component = GoodsPage;
                _params = {goods_id: rowData.adver_url};
                break;
            case 2://文章
                _component = ArticleDetail;
                _params = {
                    artID: rowData.adver_url,
                    image: rowData.adver_img,
                    title: rowData.title || rowData.adver_name
                };
                // _component =
                break;
            case 3://分类
                _component = CategoryMinPage;
                _params = {
                    title: rowData.title,
                    cate_id: rowData.adver_url,
                    country: countryIso,
                };
                // _component =
                break;
        }

        if (_component) {
            _this.props.navigator.push({
                component: _component,
                params: _params
            })
        }
    }


    /**
     * 倒计时
     * @param endDate
     * @returns {boolean|{sec: number, hours: number, min: number, days: number, millisec: number, years: number}}
     */
    getDateData(endDate) {
        endDate = endDate.replace(/-/g, "/");
        let diff = (Date.parse(new Date(endDate)) - Date.parse(new Date)) / 1000;
        // if (!!this.props.isOrederTime) {
        //     diff = (Date.parse(new Date(endDate)) + (Number(this.props.isOrederTime) * 60 * 1000) - Date.parse(new Date)) / 1000;
        // }

        if (diff <= 0) {
            return false;
        }
        const timeLeft = {
            years: 0,
            days: 0,
            hours: 0,
            min: 0,
            sec: 0,
            millisec: 0,
        };

        if (diff >= (365.25 * 86400)) {
            timeLeft.years = Math.floor(diff / (365.25 * 86400));
            diff -= timeLeft.years * 365.25 * 86400;
        }
        if (diff >= 86400) {
            timeLeft.days = Math.floor(diff / 86400);
            diff -= timeLeft.days * 86400;
        }
        if (diff >= 3600) {
            timeLeft.hours = Math.floor(diff / 3600);
            diff -= timeLeft.hours * 3600;
        }
        if (diff >= 60) {
            timeLeft.min = Math.floor(diff / 60);
            diff -= timeLeft.min * 60;
        }
        timeLeft.sec = diff;
        return timeLeft;
    }

}

// 日期月份/天的显示，如果是1位数，则在前面加上'0'
export function getFormatDate(arg) {
    if (arg === null) {
        return '';
    }

    let re = arg + '';
    if (re.length < 2) {
        re = '0' + re;
    }

    return re;
}
